package com._51doit.flinksql.test;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @create: 2021-10-31 16:11
 * @author: 今晚打脑斧先森
 * @program: StreamTableWordCount
 * @Description:
 **/
public class StreamTableWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(12345);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        DataStreamSource<String> lines = env.socketTextStream("doit01", 8086);
        SingleOutputStreamOperator<Tuple2<String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                if (value.startsWith("error")) throw new RuntimeException("data error !");
                String[] split = value.split(",");
                return Tuple2.of(split[0], Integer.parseInt(split[1]));
            }
        });
        Table table = tableEnv.fromDataStream(tpStream, $("word"), $("counts"));
        Table res = table.groupBy("word")
                .select($("word"), $("counts").sum().as("我恁爹"));
        DataStream<Tuple2<Boolean, Tuple2<String, Integer>>> tuple2DataStream = tableEnv.toRetractStream(res, TypeInformation.of(new TypeHint<Tuple2<String, Integer>>() {
        }));
        tuple2DataStream.print();
        env.execute();
    }
}
